const cityList = [
  {
    name: '南宁',
    cid: 450100,
  },
]

const TXMapKey = 'Y6EBZ-UWU6X-S734V-TI7UI-ZGV3V-7XBXS';

module.exports = function(_app,lng,lat){
  const app = getApp();
  const failHandle = () =>{
    app.globalData.userLocation.city = null;
    app.globalData.userLocation.cid = null;
  }
  wx.request({
    url: 'https://apis.map.qq.com/ws/geocoder/v1/',
    data: {
      key: TXMapKey,
      output: 'json',
      get_poi: 0,
      location: lat + ',' + lng,
    },
    header: {},
    method: 'GET',
    dataType: 'json',
    responseType: 'text',
    success: function(res) {
      // console.log(res);
      if(res.data.status === 0 && res.data.message === 'query ok'){
        for (let i in res.data.result.address_component){
          app.globalData.userLocation[i] = res.data.result.address_component[i];
        }
        for(let i of cityList){
          if (res.data.result.address_component.city.indexOf(i.name) >= 0){
            app.globalData.userLocation.cid = i.cid;
            let pages = getCurrentPages();
            for(let j of pages){
              if(j.route.indexOf('index') >= 0){ // 设置首页的城市名字
                j.setData({
                  currentCity: i.name,
                })
              }
            }
            return;
          }
        }
        // 没有匹配
        console.warn('用户位置城市未开通');
        app.globalData.userLocation.cid = '450100';
        for (let j of pages) {
          if (j.route.indexOf('index') >= 0) { // 没匹配到就是南宁
            j.setData({
              currentCity: '南宁',
            })
          }
        }
      }else {
        failHandle();
      }
    },
    fail: function(res) {
      failHandle();
    },
    complete: function(res) {},
  })
}